<template>
  <div class="page">
    <h2>基数药补药申请</h2>

    <div class="controls">
      <el-input v-model="q" placeholder="按药品名称/编码/申请人搜索" clearable style="flex:1" @clear="onClear" />
      <el-select v-model="filterStatus" placeholder="全部状态" style="width:160px">
        <el-option label="全部" :value="''" />
        <el-option label="待处理" value="pending" />
        <el-option label="已批准" value="approved" />
        <el-option label="已拒绝" value="rejected" />
      </el-select>
      <div style="display:flex;gap:8px">
        <el-button type="primary" @click="openModal()">新建申请</el-button>
        <el-button @click="exportCSV">导出CSV</el-button>
      </div>
    </div>

    <div class="muted">注：演示数据静态存放，实际系统应结合库存与审批流程自动流转并记录日志。</div>

    <el-table :data="filtered" stripe border style="width:100%;margin-top:12px" @selection-change="onSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="申请单号" width="120" />
      <el-table-column prop="drugName" label="药品" />
      <el-table-column prop="requestedQty" label="申请数量" width="120" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="applicant" label="申请人/科室" width="180" />
      <el-table-column prop="createdAt" label="申请时间" width="180" />
      <el-table-column prop="status" label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status==='pending'?'info':(row.status==='approved'?'success':'danger')">{{ statusLabel(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template #default="{ row }">
          <el-button size="small" @click="view(row.id)">查看</el-button>
          <el-button size="small" type="primary" @click="approve(row.id)" v-if="row.status==='pending'" style="margin-left:8px">批准</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin-top:8px;display:flex;gap:8px;align-items:center">
      <el-button type="danger" @click="batchDelete">批量删除</el-button>
      <div style="flex:1"></div>
      <div class="muted">已选：{{ selectedIds.length }} 项 / 总计：{{ filtered.length }} 条</div>
    </div>

    <el-dialog title="补药申请" v-model="showModal" width="520px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="药品编码/名称">
          <el-input v-model="form.drug" placeholder="例如：S-002 劳拉西泮片" />
        </el-form-item>
        <el-form-item label="申请数量">
          <el-input-number v-model="form.requestedQty" :min="1" />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="form.unit" />
        </el-form-item>
        <el-form-item label="申请人/科室">
          <el-input v-model="form.applicant" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="form.note" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeModal">取消</el-button>
        <el-button type="primary" @click="submit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

const q = ref('');
const filterStatus = ref('');
const data = ref([]);
const selectedRows = ref([]);
const selectedIds = ref([]);
const showModal = ref(false);
const form = reactive({ drug:'', requestedQty:1, unit:'盒', applicant:'', note:'' });

const DEFAULT = [
  { id:'R-1001', drugName:'劳拉西泮片', requestedQty:50, unit:'盒', applicant:'门诊/精神科', createdAt:'2025-10-20 10:12', status:'pending' },
  { id:'R-1002', drugName:'氟哌啶醇注射液', requestedQty:20, unit:'支', applicant:'住院/急诊', createdAt:'2025-10-18 09:34', status:'approved' },
  { id:'R-1003', drugName:'奥氮平片', requestedQty:30, unit:'盒', applicant:'门诊/综合', createdAt:'2025-10-15 14:20', status:'rejected' }
];

onMounted(()=>{ data.value = JSON.parse(JSON.stringify(DEFAULT)); });

const filtered = computed(()=>{
  const qq = q.value.trim().toLowerCase();
  return data.value.filter(d=>{
    if(qq && !(d.drugName.toLowerCase().includes(qq) || d.id.toLowerCase().includes(qq) || d.applicant.toLowerCase().includes(qq))) return false;
    if(filterStatus.value && d.status !== filterStatus.value) return false;
    return true;
  });
});

function statusLabel(s){ if(s==='pending') return '待处理'; if(s==='approved') return '已批准'; return '已拒绝'; }
function onSelectionChange(rows){ selectedRows.value = rows; selectedIds.value = rows.map(r=>r.id); }
function openModal(){ Object.assign(form,{drug:'',requestedQty:1,unit:'盒',applicant:'',note:''}); showModal.value=true; }
function closeModal(){ showModal.value=false; }
function submit(){ if(!form.drug || !form.requestedQty || !form.applicant){ ElMessage.warning('请完整填写申请信息'); return; }
  const nid = 'R-'+(1000 + data.value.length + 1);
  data.value.unshift({ id:nid, drugName: form.drug, requestedQty: form.requestedQty, unit: form.unit, applicant: form.applicant, createdAt: new Date().toISOString().slice(0,16).replace('T',' '), status:'pending' });
  showModal.value=false; ElMessage.success('申请已提交（演示）'); }

function view(id){ const it = data.value.find(x=>x.id===id); if(it) ElMessage.info(JSON.stringify(it)); }
function approve(id){ const it = data.value.find(x=>x.id===id); if(!it) return; ElMessageBox.confirm('批准该申请吗？','审批确认',{confirmButtonText:'批准',cancelButtonText:'取消',type:'warning'})
  .then(()=>{ it.status='approved'; ElMessage.success('已批准（演示）'); })
  .catch(()=>{});
}
function batchDelete(){ const ids = selectedIds.value; if(ids.length===0){ ElMessage.warning('请选择项'); return; } ElMessageBox.confirm(`确认删除 ${ids.length} 条申请？`,'删除',{confirmButtonText:'确定',cancelButtonText:'取消',type:'warning'})
  .then(()=>{ data.value = data.value.filter(d=>!ids.includes(d.id)); selectedIds.value = []; selectedRows.value = []; ElMessage.success('删除完成'); })
  .catch(()=>{});
}
function exportCSV(){ const rows = [['id','drugName','requestedQty','unit','applicant','createdAt','status'], ...data.value.map(r=>[r.id,r.drugName,r.requestedQty,r.unit,r.applicant,r.createdAt,r.status])]; const txt = rows.map(r=>r.map(c=>`"${String(c).replace(/"/g,'""')}"`).join(',')).join('\n'); const blob = new Blob([txt],{type:'text/csv'}); const url = URL.createObjectURL(blob); const a=document.createElement('a'); a.href=url; a.download='replenishment_requests.csv'; a.click(); URL.revokeObjectURL(url); }
function onClear(){}
</script>

<style scoped>
.page{font-family: Arial, "Microsoft YaHei", sans-serif; margin:10px;}
h2{margin-top:-10px}
.controls{display:flex;gap:8px;margin-bottom:12px;align-items:center}
.muted{color:#666;font-size:13px}
</style>